package com.campus.client.view;


import com.campus.client.controller.ShopController;
import com.campus.common.type.BuyResult;
import com.campus.common.vo.Product;

import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.paint.Color;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

public class ShopFrame {

    private ShopController shopController;
    private GridPane productGrid;
    private ScrollPane scrollPane;
    private VBox categoryBox;
    private Label welcomeLabel;
    private HBox searchBox;
    private Button backButton;

    private User user=new User();
    public User getUser() {return user;}
    public void setUser(String Id,String password,String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
        //System.out.print("用户名"+this.user.getId());
    }


    private final int COLS = 4;

    private Map<Product, Integer> cart = new HashMap<>();

    public void start(Stage primaryStage) throws Exception {
        shopController = new ShopController(new com.campus.client.net.ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // ====== 顶部标题栏 ======
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("虚拟校园商店 - 学生教师版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 添加返回按钮
        backButton = createStyledButton("返回");
        backButton.getStyleClass().add("secondary-button");
        backButton.setOnAction(e -> {
            try {
                back();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        Button cartButton = createStyledButton("查看购物车");
        cartButton.getStyleClass().add("primary-button");
        cartButton.setOnAction(e -> showCart());

        headerBox.getChildren().addAll(titleLabel, spacer, cartButton, buttonSpacer, backButton);
        root.setTop(headerBox);

        // ====== 左侧分类栏 ======
        categoryBox = createCategoryAccordion();
        root.setLeft(categoryBox);

        // ====== 中间内容区 ======
        VBox contentBox = new VBox(20);
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));
        contentBox.setAlignment(Pos.TOP_CENTER); 

        welcomeLabel = new Label("欢迎来到校园商店！");
        welcomeLabel.setStyle("-fx-font-size: 28px; -fx-font-weight: bold; -fx-text-fill: #0d1b4c;");
        
        searchBox = new HBox(10);
        searchBox.setAlignment(Pos.CENTER);
        TextField searchField = new TextField();
        searchField.setPromptText("输入商品名称搜索...");
        searchField.setPrefWidth(400);
        Button searchBtn = createStyledButton("搜索");
        searchBtn.getStyleClass().add("primary-button");
        searchBtn.setOnAction(e -> searchProducts(searchField.getText()));
        searchBox.getChildren().addAll(searchField, searchBtn);
        
        productGrid = new GridPane();
        productGrid.setHgap(20);
        productGrid.setVgap(20);
        productGrid.setPadding(new Insets(10));
        productGrid.setAlignment(Pos.TOP_CENTER);

        scrollPane = new ScrollPane(productGrid);
        scrollPane.getStyleClass().add("scroll-pane");
        scrollPane.setFitToWidth(true);

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 默认显示首页：热卖/上新
        loadHomeProducts();

        Scene scene = new Scene(root, 1200, 700);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("校园商店 - 学生教师版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    // 根据是否首页显示欢迎词和搜索框
    private void showHomeHeader(boolean show) {
        VBox contentBox = (VBox) scrollPane.getParent();
        contentBox.getChildren().clear();
        if (show) {
            contentBox.getChildren().addAll(welcomeLabel, searchBox, scrollPane);
        } else {
            contentBox.getChildren().add(scrollPane);
        }
    }


    private void searchProducts(String keyword) {
        productGrid.getChildren().clear();
        try {
            List<Product> allProducts = shopController.getProducts();
            List<Product> result = allProducts.stream()
                    .filter(p -> p.getPname().toLowerCase().contains(keyword.toLowerCase()))
                    .collect(Collectors.toList());

            if (result.isEmpty()) {
                Label emptyLabel = new Label("未找到相关商品");
                emptyLabel.getStyleClass().add("section-title");
                productGrid.add(emptyLabel, 0, 0, COLS, 1);
            } else {
                for (int i = 0; i < result.size(); i++) {
                    Product p = result.get(i);
                    VBox productBox = createProductBox(p);
                    int col = i % COLS;
                    int row = i / COLS;
                    productGrid.add(productBox, col, row);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "搜索失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }


	// ====== 左侧分类栏 ======
    private VBox createCategoryAccordion() {
        VBox leftBox = new VBox(10);
        leftBox.setPadding(new Insets(10));
        leftBox.setStyle("-fx-background-color: #e3eafc; -fx-background-radius: 8;");

        Label title = new Label("商品分类");
        title.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        // 首页按钮
        Button homeBtn = createStyledButton("首页");
        homeBtn.setOnAction(e -> loadHomeProducts());

        // 折叠面板
        Accordion accordion = new Accordion();

        // ===== 饮食分类 =====
        VBox foodBox = new VBox(5);
        Button foodBtn = createStyledButton("食物");
        foodBtn.setOnAction(e -> loadProductsByCategory("食物"));
        Button drinkBtn = createStyledButton("饮料");
        drinkBtn.setOnAction(e -> loadProductsByCategory("饮料"));
        foodBox.getChildren().addAll(foodBtn, drinkBtn);
        TitledPane foodPane = new TitledPane("饮食", foodBox);

        // ===== 学习分类 =====
        VBox studyBox = new VBox(5);
        Button stationeryBtn = createStyledButton("文具");
        stationeryBtn.setOnAction(e -> loadProductsByCategory("文具"));
        studyBox.getChildren().addAll(stationeryBtn);
        TitledPane studyPane = new TitledPane("学习", studyBox);

        // ===== 生活分类 =====
        VBox lifeBox = new VBox(5);
        Button dailyBtn = createStyledButton("日用品");
        dailyBtn.setOnAction(e -> loadProductsByCategory("日用品"));
        lifeBox.getChildren().addAll(dailyBtn);
        TitledPane lifePane = new TitledPane("生活", lifeBox);
        
        // ===== 临期商品分类 =====
        VBox expireBox = new VBox(5);
        Button expireBtn = createStyledButton("临期商品");
        expireBtn.setOnAction(e -> loadExpiredProducts());
        expireBox.getChildren().addAll(expireBtn);
        TitledPane expirePane = new TitledPane("优惠商品", expireBox);

        // 加入 Accordion
        accordion.getPanes().addAll(foodPane, studyPane, lifePane, expirePane);

        leftBox.getChildren().addAll(title, homeBtn, accordion);
        return leftBox;
    }

    // ====== 首页：热卖和上新 ======
    private void loadHomeProducts() {
    	showHomeHeader(true); // 首页显示欢迎词和搜索框
        productGrid.getChildren().clear();
        try {
            List<Product> allProducts = shopController.getProducts();

            // 热卖
            List<Product> hotProducts = allProducts.stream()
                    .filter(p -> p.getHot() == 1 && p.getStatus() == 1)
                    .collect(Collectors.toList());
            if (!hotProducts.isEmpty()) {
                Label hotLabel = new Label("🔥 最近热卖");
                hotLabel.getStyleClass().add("section-title");
                productGrid.add(hotLabel, 0, 0, COLS, 1);

                int rowOffset = 1;
                for (int i = 0; i < hotProducts.size(); i++) {
                    Product p = hotProducts.get(i);
                    ImageView imgView = new ImageView();
                    imgView.setFitWidth(150);
                    imgView.setFitHeight(150);
                    loadProductImage(p, imgView);
                    styleHomeImage(imgView, p);

                    int col = i % COLS;
                    int row = (i / COLS) + rowOffset;
                    productGrid.add(imgView, col, row);
                }
            }

            // 上新
            List<Product> newProducts = allProducts.stream()
                    .filter(p -> p.getNewP() == 1 && p.getStatus() == 1)
                    .collect(Collectors.toList());
            if (!newProducts.isEmpty()) {
                int startRow = hotProducts.size() / COLS + 2;
                Label newLabel = new Label("🆕 最近上新");
                newLabel.getStyleClass().add("section-title");
                productGrid.add(newLabel, 0, startRow, COLS, 1);

                int rowOffset = startRow + 1;
                for (int i = 0; i < newProducts.size(); i++) {
                    Product p = newProducts.get(i);
                    ImageView imgView = new ImageView();
                    imgView.setFitWidth(150);
                    imgView.setFitHeight(150);
                    loadProductImage(p, imgView);
                    styleHomeImage(imgView, p);

                    int col = i % COLS;
                    int row = (i / COLS) + rowOffset;
                    productGrid.add(imgView, col, row);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载首页商品失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ====== 首页图片样式 ======
    private void styleHomeImage(ImageView imageView, Product p) {
        // 阴影 + 边框 + 圆角
        imageView.setStyle("-fx-effect: dropshadow(gaussian, rgba(0,0,0,0.3), 10, 0, 0, 2);"
                + "-fx-border-color: #0d1b4c;"
                + "-fx-border-width: 2;"
                + "-fx-border-radius: 10;"
                + "-fx-background-radius: 10;");

        // 鼠标悬停放大
        imageView.setOnMouseEntered(e -> {
            imageView.setScaleX(1.1);
            imageView.setScaleY(1.1);
        });
        imageView.setOnMouseExited(e -> {
            imageView.setScaleX(1.0);
            imageView.setScaleY(1.0);
        });

        // 点击显示详情
        imageView.setOnMouseClicked(e -> loadProductDetail(p));
    }
    
    private void loadExpiredProducts() {
        showHomeHeader(false);
        productGrid.getChildren().clear();
        try {
            List<Product> allProducts = shopController.getProducts();

            // 过滤：食物或饮料，且临期标记 == 1
            List<Product> products = allProducts.stream()
                    .filter(p -> ("食物".equals(p.getCategory()) || "饮料".equals(p.getCategory()))
                            && p.getStatus() == 1
                            && p.getExpireSoon() == 1) 
                    .collect(Collectors.toList());

            Label categoryLabel = new Label("临期商品（七折优惠）");
            categoryLabel.getStyleClass().add("section-title");
            productGrid.add(categoryLabel, 0, 0, COLS, 1);

            for (int i = 0; i < products.size(); i++) {
                Product p = products.get(i);
                VBox productBox = createProductBox(p);
                int col = i % COLS;
                int row = (i / COLS) + 1;
                productGrid.add(productBox, col, row);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载临期商品失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }



    // ====== 加载指定类别商品 ======
    private void loadProductsByCategory(String category) {
    	showHomeHeader(false); // 分类页不显示欢迎词和搜索框
    	productGrid.getChildren().clear();
        try {
            List<Product> allProducts = shopController.getProducts();
            List<Product> products = allProducts.stream()
                    .filter(p -> category.equals(p.getCategory()) && p.getStatus() == 1)
                    .collect(Collectors.toList());

            Label categoryLabel = new Label(category + "列表");
            categoryLabel.getStyleClass().add("section-title");
            productGrid.add(categoryLabel, 0, 0, COLS, 1);

            for (int i = 0; i < products.size(); i++) {
                Product p = products.get(i);
                VBox productBox = createProductBox(p);
                int col = i % COLS;
                int row = (i / COLS) + 1;
                productGrid.add(productBox, col, row);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载商品失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ====== 商品卡片 ======
    private VBox createProductBox(Product p) {
        VBox box = new VBox(10);
        box.setPadding(new Insets(15));
        box.getStyleClass().add("product-card");
        box.setAlignment(Pos.TOP_CENTER);

        ImageView imageView = new ImageView();
        imageView.setFitWidth(180);
        imageView.setFitHeight(180);
        loadProductImage(p, imageView);
        imageView.setOnMouseClicked(e -> loadProductDetail(p));

        Label nameLabel = new Label(p.getPname());
        nameLabel.getStyleClass().add("product-name");
        
        double price = p.getPrice();
        HBox priceBox = new HBox(5);
        priceBox.setAlignment(Pos.CENTER);
        
        if (p.getExpireSoon() == 1) {
            double newPrice = price * 0.7; // 七折
            
            Text oldPriceText = new Text("¥" + String.format("%.2f", price));
            oldPriceText.setFill(Color.GRAY);
            oldPriceText.setFont(Font.font("System", FontWeight.NORMAL, 14));
            oldPriceText.setStrikethrough(true);

            Text newPriceText = new Text("¥" + String.format("%.2f", newPrice));
            newPriceText.setFill(Color.RED);
            newPriceText.setFont(Font.font("System", FontWeight.BOLD, 18));
            priceBox.getChildren().addAll(oldPriceText, newPriceText);
        } else {
        	Label priceLabel = new Label("¥" + String.format("%.2f", price));
            priceLabel.getStyleClass().add("product-price");
            priceBox.getChildren().add(priceLabel);
        }

        Label stockLabel = new Label("库存: " + p.getStock());
        stockLabel.getStyleClass().add("product-stock");

        Label descLabel = new Label("描述: " + p.getDesc());
        descLabel.getStyleClass().add("product-desc");

        HBox quantityBox = new HBox(5);
        quantityBox.setAlignment(Pos.CENTER);
        Label quantityLabel = new Label("数量:");
        quantityLabel.getStyleClass().add("form-label");
        Spinner<Integer> qtySpinner = new Spinner<>(1, Integer.MAX_VALUE, 1);
        qtySpinner.getStyleClass().add("quantity-spinner");
        qtySpinner.setEditable(true);
        quantityBox.getChildren().addAll(quantityLabel, qtySpinner);

        Button buyButton = createStyledButton("加入购物车");
        buyButton.getStyleClass().add("primary-button");
        buyButton.setOnAction(e -> {
            int qty = qtySpinner.getValue();
            int currentInCart = cart.getOrDefault(p, 0);
            int totalRequested = currentInCart + qty;
            if (qty <= 0) {
                showAlert("警告", "数量必须大于0！", Alert.AlertType.WARNING);
                return;
            }
            if (totalRequested > p.getStock()) {
                showAlert("警告", "库存不足！当前库存为 " + p.getStock() +
                        "，购物车已有 " + currentInCart + " 件。", Alert.AlertType.WARNING);
                return;
            }
            cart.put(p, totalRequested);
            showAlert("成功", p.getPname() + " × " + qty +
                    " 已加入购物车！（购物车总数：" + totalRequested + "）", Alert.AlertType.INFORMATION);
        });

        box.getChildren().addAll(imageView, nameLabel, priceBox, stockLabel, descLabel, quantityBox, buyButton);
        return box;
    }

    // ====== 商品详情弹窗 ======
    private void loadProductDetail(Product p) {
        Stage detailStage = new Stage();
        detailStage.setTitle(p.getPname() + " - 商品详情");

        VBox root = new VBox(15);
        root.setPadding(new Insets(20));
        root.setAlignment(Pos.CENTER);
        root.getStyleClass().add("dialog-container");

        ImageView imageView = new ImageView();
        imageView.setFitWidth(300);
        imageView.setFitHeight(300);
        loadProductImage(p, imageView);

        Label nameLabel = new Label(p.getPname());
        nameLabel.getStyleClass().add("product-name");

        // 价格显示
        HBox priceBox = new HBox(5);
        priceBox.setAlignment(Pos.CENTER);
        double price = p.getPrice();
        if (p.getExpireSoon() == 1) {
            double newPrice = price * 0.7; // 七折

            Text oldPriceText = new Text("¥" + String.format("%.2f", price));
            oldPriceText.setFill(Color.GRAY);
            oldPriceText.setFont(Font.font("System", FontWeight.NORMAL, 14));
            oldPriceText.setStrikethrough(true);

            Text newPriceText = new Text("¥" + String.format("%.2f", newPrice));
            newPriceText.setFill(Color.RED);
            newPriceText.setFont(Font.font("System", FontWeight.BOLD, 18));
            priceBox.getChildren().addAll(oldPriceText, newPriceText);
        
        } else {
            Label priceLabel = new Label("¥" + String.format("%.2f", price));
            priceLabel.getStyleClass().add("product-price");
            priceBox.getChildren().add(priceLabel);
        }
        
        Label stockLabel = new Label("库存: " + p.getStock());
        stockLabel.getStyleClass().add("product-stock");

        Label descLabel = new Label("描述: " + p.getDesc());
        descLabel.getStyleClass().add("product-desc");

        HBox quantityBox = new HBox(5);
        quantityBox.setAlignment(Pos.CENTER);
        Label quantityLabel = new Label("数量:");
        quantityLabel.getStyleClass().add("form-label");
        Spinner<Integer> qtySpinner = new Spinner<>(1, p.getStock(), 1);
        qtySpinner.getStyleClass().add("quantity-spinner");
        qtySpinner.setEditable(true);
        quantityBox.getChildren().addAll(quantityLabel, qtySpinner);

        Button buyButton = createStyledButton("加入购物车");
        buyButton.getStyleClass().add("primary-button");
        buyButton.setOnAction(e -> {
            int qty = qtySpinner.getValue();
            int currentInCart = cart.getOrDefault(p, 0);
            int totalRequested = currentInCart + qty;
            if (totalRequested > p.getStock()) {
                showAlert("警告", "库存不足！当前库存为 " + p.getStock() +
                        "，购物车已有 " + currentInCart + " 件。", Alert.AlertType.WARNING);
                return;
            }
            cart.put(p, totalRequested);
            showAlert("成功", p.getPname() + " × " + qty +
                    " 已加入购物车！（购物车总数：" + totalRequested + "）", Alert.AlertType.INFORMATION);
        });

        root.getChildren().addAll(imageView, nameLabel, priceBox, stockLabel, descLabel, quantityBox, buyButton);

        Scene scene = new Scene(root, 400, 600);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        detailStage.setScene(scene);
        detailStage.show();
    }

    // ====== 加载商品图片 ======
    private void loadProductImage(Product p, ImageView imageView) {
        try {
            byte[] data = shopController.getProductImageBytes(p.getImageUrl());
            if (data != null) {
                InputStream is = new ByteArrayInputStream(data);
                Image img = new Image(is, imageView.getFitWidth(), imageView.getFitHeight(), true, true);
                imageView.setImage(img);
            } else {
                // 默认图
                imageView.setImage(new Image(getClass().getResource("/default.png").toString(),
                        imageView.getFitWidth(), imageView.getFitHeight(), true, true));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public void back() throws IOException {
        // 获取当前登录窗口的Stage
        Stage passwordChangeStage = (Stage) backButton.getScene().getWindow();

        if(user.getRole().equals("教师")){
            TeacherMainFrame teacherMainFrame = new TeacherMainFrame();
            teacherMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());
            Stage stage = new Stage();
            teacherMainFrame.show(stage);
        }else{
            StudentMainFrame studentMainFrame = new StudentMainFrame();
            studentMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());
            Stage stage = new Stage();
            studentMainFrame.show(stage);
        }

        passwordChangeStage.close();
    }

    // ====== 购物车界面 ======
    private void showCart() {
        Stage cartStage = new Stage();
        cartStage.setTitle("购物车");

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(15));
        root.getStyleClass().add("dialog-container");

        Label titleLabel = new Label("我的购物车");
        titleLabel.getStyleClass().add("dialog-title");
        BorderPane.setAlignment(titleLabel, Pos.CENTER);
        root.setTop(titleLabel);

        VBox cartContent = new VBox(10);
        cartContent.setPadding(new Insets(15));

        if (cart.isEmpty()) {
            Label emptyLabel = new Label("购物车为空");
            emptyLabel.getStyleClass().add("empty-label");
            cartContent.getChildren().add(emptyLabel);
        } else {
            // 遍历购物车商品
            for (Map.Entry<Product, Integer> entry : cart.entrySet()) {
                Product p = entry.getKey();
                int qty = entry.getValue();

                HBox itemRow = new HBox(15);
                itemRow.setPadding(new Insets(10));
                itemRow.getStyleClass().add("cart-item");
                itemRow.setAlignment(Pos.CENTER_LEFT);

                ImageView imageView = new ImageView();
                imageView.setFitWidth(60);
                imageView.setFitHeight(60);
                loadProductImage(p, imageView);

                VBox infoBox = new VBox(5);
                Label nameLabel = new Label(p.getPname());
                nameLabel.getStyleClass().add("product-name");
                
                double price = p.getPrice();
                if (p.getExpireSoon() == 1) {
                    price *= 0.7;
                }
                Label priceLabel = new Label("¥" + String.format("%.2f", price));
                priceLabel.getStyleClass().add("product-price");
                infoBox.getChildren().addAll(nameLabel, priceLabel);

                HBox controlBox = new HBox(10);
                controlBox.setAlignment(Pos.CENTER);
                Label quantityLabel = new Label("数量:");
                quantityLabel.getStyleClass().add("form-label");
                Spinner<Integer> qtySpinner = new Spinner<>(0, p.getStock(), qty);
                qtySpinner.getStyleClass().add("quantity-spinner");
                qtySpinner.setEditable(true);

                Button updateBtn = createStyledButton("确认更改");
                updateBtn.getStyleClass().add("small-button");
                updateBtn.setOnAction(e -> {
                    int newQty = qtySpinner.getValue();
                    if (newQty > p.getStock()) {
                        showAlert("警告", "库存不足！当前库存为 " + p.getStock(), Alert.AlertType.WARNING);
                        qtySpinner.getValueFactory().setValue(cart.get(p));
                        return;
                    }
                    if (newQty == 0) {
                        cart.remove(p);
                    } else {
                        cart.put(p, newQty);
                    }
                    refreshCartView(cartStage);
                });

                Button deleteBtn = createStyledButton("删除");
                deleteBtn.getStyleClass().add("danger-button");
                deleteBtn.setOnAction(e -> {
                    cart.remove(p);
                    refreshCartView(cartStage);
                });

                controlBox.getChildren().addAll(quantityLabel, qtySpinner, updateBtn, deleteBtn);
                itemRow.getChildren().addAll(imageView, infoBox, controlBox);
                cartContent.getChildren().add(itemRow);
            }

            // 总价
            double total = 0.0;
            for (Map.Entry<Product, Integer> entry : cart.entrySet()) {
                Product p = entry.getKey();
                int qty = entry.getValue();
                
                double price = p.getPrice();
                if (p.getExpireSoon() == 1) {
                    price *= 0.7;  // 临期七折
                }
                total += price * qty;
            }

            Label totalLabel = new Label("总价: ¥" + String.format("%.2f", total));
            totalLabel.getStyleClass().add("total-label");

            // 底部按钮
            HBox buttonBox = new HBox(15);
            buttonBox.setAlignment(Pos.CENTER_RIGHT);
            buttonBox.setPadding(new Insets(15, 0, 0, 0));

            Button clearBtn = createStyledButton("清空购物车");
            clearBtn.getStyleClass().add("secondary-button");
            clearBtn.setOnAction(e -> {
                cart.clear();
                refreshCartView(cartStage);
            });

            Button confirmBtn = createStyledButton("确认购买");
            confirmBtn.getStyleClass().add("primary-button");
            confirmBtn.setOnAction(e -> {
                try {
                    if (cart.isEmpty()) {
                        showAlert("提示", "购物车为空！", Alert.AlertType.INFORMATION);
                        return;
                    }
                    
                    TextInputDialog pwdDialog = new TextInputDialog();
                    pwdDialog.setTitle("请输入密码");
                    pwdDialog.setHeaderText("为了安全，请输入您的账户密码进行验证");
                    pwdDialog.setContentText("密码：");

                    Optional<String> inputResult = pwdDialog.showAndWait();
                    if (!inputResult.isPresent()) {
                        // 用户取消输入
                        return;
                    }
                    String inputPwd = inputResult.get();

                    // 构造批量购买列表
                    List<Integer> productIds = new ArrayList<>();
                    List<Integer> quantities = new ArrayList<>();
                    for (Map.Entry<Product, Integer> entry : cart.entrySet()) {
                        productIds.add(entry.getKey().getPid());
                        quantities.add(entry.getValue());
                    }

                    // 调用批量购买接口
                    BuyResult result = shopController.buyProducts(productIds, quantities, user.getId(), inputPwd);

                    switch (result) {
                        case SUCCESS:
                            cart.clear();
                            showAlert("成功", "购买成功！", Alert.AlertType.INFORMATION);
                            cartStage.close();
                            loadHomeProducts(); // 刷新首页
                            break;
                        case INSUFFICIENT_STOCK:
                            showAlert("失败", "有商品库存不足，请调整购物车！", Alert.AlertType.WARNING);
                            break;
                        case INSUFFICIENT_BALANCE:
                            showAlert("失败", "账户余额不足，无法购买全部商品！", Alert.AlertType.WARNING);
                            break;
                        case INCORRECT_PASSWORD:
                            showAlert("失败", "密码错误，请重新输入密码！", Alert.AlertType.WARNING);
                            break;
                        default:
                            showAlert("失败", "购买失败（未知原因）", Alert.AlertType.WARNING);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "购买失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            });


            buttonBox.getChildren().addAll(clearBtn, confirmBtn);
            cartContent.getChildren().addAll(totalLabel, buttonBox);
        }

        ScrollPane scrollPane = new ScrollPane(cartContent);
        scrollPane.getStyleClass().add("scroll-pane");
        root.setCenter(scrollPane);

        Scene scene = new Scene(root, 600, 500);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        cartStage.setScene(scene);
        cartStage.show();
    }

    private void refreshCartView(Stage cartStage) {
        cartStage.close();
        showCart();
    }

    private void showAlert(String title, String msg, Alert.AlertType type) {
        Alert alert = new Alert(type, msg, ButtonType.OK);
        alert.setTitle(title);
        alert.showAndWait();
    }

    private Button createStyledButton(String text) {
        Button btn = new Button(text);
        btn.getStyleClass().add("btn");
        return btn;
    }

}
